/**
 * @Title: ExcelController.java
 * @Package com.lemon.controller.excel
 * @Description: (一句话阐述):
 * @author Ran_cc
 * @date 2018年8月10日
 * @version V1.0
 */
package com.lemon.controller.excel;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lemon.conf.MyException;
import com.lemon.model.cityRun.CrShops;
import com.lemon.service.cityRun.CrShopsService;
import com.lemon.utils.ReqResult;
import com.lemon.utils.StringUtil;

/**
 * <p>
 * Title: ExcelController
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author Ran_cc
 * @date 2018年8月10日
 * @版本 V 1.0
 */
@RestController
@RequestMapping("/excel")
public class ExcelController {

	@Autowired(required = true)
	private ExcelService excelService;
	@Resource
	private CrShopsService shopService;
	//导入excel
	@RequestMapping(value = "/import" , method = RequestMethod.POST)
	public Map<String , Object> importExcel(@RequestParam(value = "file" , required = false) MultipartFile file ,
			HttpServletRequest request , HttpServletResponse response) {

		Map<String , Object> map = new HashMap<String , Object>();
		String result = excelService.readExcelFile(file);
		map.put("message" , result);
		return map;
	}

	//导入excel
	@RequestMapping(value = "/pintuan" , method = RequestMethod.POST)
	public Map<String , Object> pintuan(@RequestParam(value = "file" , required = false) MultipartFile file ,
			HttpServletRequest request , HttpServletResponse response) {

		Map<String , Object> map = new HashMap<String , Object>();
		String result = excelService.readPinTuanExcelFile(file);
		map.put("message" , result);
		return map;
	}

	//导入excel
	@RequestMapping(value = "/exportShopDataStatis")
	public void shopDataStatis(@ModelAttribute CrShops crShops , HttpServletRequest request ,
			HttpServletResponse response) {
		try {
			crShops.setWhere(" and (a.shop_status =1 or  a.shop_status =2 or a.shop_status = 3)");
			crShops.setPageSize(10000000);
			List<CrShops> shops = shopService.getShopOrderProfitInfo(crShops);
			if (shops.size()<=0) {
				return;
			}
			//excel标题
			String[] title = { "门店名称" , "地区" , "入住费用(元)" , "订单数" , "订单收入(元)" , "外卖收入(元)" , "堂食收入(元)" , "微信支付(元)" ,
					"现金结算(元)" };
			//excel文件名
			String fileName = "数据统计-" + StringUtil.getPastDate(0) + ".xls";

			//sheet名
			String sheetName = "数据统计";
			
			DecimalFormat f = new DecimalFormat("0.00");
			String [][] content = new String[shops.size()][title.length];
			for (int i = 0; i < shops.size(); i++) {
	            content[i] = new String[title.length];
	            CrShops s = shops.get(i);
	            content[i][0] = s.getShopTitle().toString();
				content[i][1] = s.getAddressProvince().toString() + s.getAddressCity().toString()
						+ s.getAddressArea().toString();
				content[i][2] = f.format((s.getShopInCharge() / 100.0));
				content[i][3] = s.getOrderCount().toString();
				content[i][4] = f.format(Integer.parseInt(s.getPayCount()) / 100.0);
				content[i][5] = f.format(Integer.parseInt(s.getOutCount()) / 100.0);
				content[i][6] = f.format(Integer.parseInt(s.getRoomCount()) / 100.0);
				content[i][7] = f.format(Integer.parseInt(s.getWxCount()) / 100.0);
				content[i][8] = f.format(Integer.parseInt(s.getXxCount()) / 100.0);
			}
			//创建HSSFWorkbook 
			HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName , title , content , null);
			this.setResponseHeader(response , fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			MyException.writeErr(e , "");
		}
	}

	public static void main(String[] args) {
		DecimalFormat f = new DecimalFormat("0.00");
		String s = f.format(100001 / 100.0);
		System.out.println(s);
	}
	@RequestMapping(value = "/cityDownExcel.do")
	public void cityDownExcel(HttpServletResponse response,HttpServletRequest request) {
        try {
            //获取文件的路径
			//String excelPath = request.getSession().getServletContext().getRealPath("/Excel/"+"荒.xls");
			String fileName = "城跑-菜品批量导入模板.xlsx".toString(); // 文件的默认保存名
            // 读到流中
			//			InputStream inStream = new FileInputStream("/src/main/resources/files/城跑-菜品批量导入模板.xlsx");//文件的存放路径dsd
			InputStream inStream = getClass().getResourceAsStream("/files/goods_add_temp.xlsx");
			System.out.println(inStream);
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition",
					"attachment;filename=" + URLEncoder.encode(fileName , "UTF-8"));
            // 循环取出流中的数据
            byte[] b = new byte[200];
            int len;
 
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}

	//导入excel
	@RequestMapping(value = "/importGoods" , method = RequestMethod.POST)
	public ReqResult importGoods(@RequestParam(value = "file" , required = false) MultipartFile file ,
			String shopId ,
			HttpServletRequest request , HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String result = excelService.readGoodsFile(file , shopId);
			reqResult.setReturnResult("succ");
		} catch (Exception e) {
			if (StringUtil.isNotBlank(e.getMessage())) {
				int ii = e.getMessage().indexOf("没有被创建");
				if (ii >= 0) {
					reqResult.setReturnResult(e.getMessage() , ReqResult.code_error);
				} else {
					reqResult.setReturnResult("导入失败，商品信息有误，请核对后重新导入！" , ReqResult.code_error);
				}
			}
			MyException.writeErr(e , "导入菜品异常");
		}
		return reqResult;
	}

	@RequestMapping(value = "/downGoodsTypeExcel.do")
	public void downGoodsTypeExcel(HttpServletResponse response , HttpServletRequest request) {
		try {
			//获取文件的路径
			//String excelPath = request.getSession().getServletContext().getRealPath("/Excel/"+"荒.xls");
			String fileName = "城跑-菜品分类批量导入模板.xlsx".toString(); // 文件的默认保存名
			// 读到流中
			//			InputStream inStream = new FileInputStream("/src/main/resources/files/城跑-菜品批量导入模板.xlsx");//文件的存放路径dsd
			InputStream inStream = getClass().getResourceAsStream("/files/goods_type_add_temp.xlsx");
			System.out.println(inStream);
			// 设置输出的格式
			response.reset();
			response.setContentType("bin");
			response.addHeader("Content-Disposition" , "attachment;filename=" + URLEncoder.encode(fileName , "UTF-8"));
			// 循环取出流中的数据
			byte[] b = new byte[200];
			int len;

			while ((len = inStream.read(b)) > 0) {
				response.getOutputStream().write(b , 0 , len);
			}
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//导入excel
	@RequestMapping(value = "/importGoodsType" , method = RequestMethod.POST)
	public ReqResult importGoodsType(@RequestParam(value = "file" , required = false) MultipartFile file ,
			String shopId , HttpServletRequest request , HttpServletResponse response) {
		ReqResult reqResult = new ReqResult();
		try {
			String result = excelService.readGoodsTypeFile(file , shopId);
			reqResult.setReturnResult("succ");
		} catch (Exception e) {
			if (StringUtil.isNotBlank(e.getMessage())) {
				int ii = e.getMessage().indexOf("没有被创建");
				if (ii >= 0) {
					reqResult.setReturnResult(e.getMessage() , ReqResult.code_error);
				} else {
					reqResult.setReturnResult("导入失败，商品分类信息有误，请核对后重新导入！" , ReqResult.code_error);
				}
			}
			MyException.writeErr(e , "导入菜品分类异常");
		}
		return reqResult;
	}
	//发送响应流方法
	public void setResponseHeader(HttpServletResponse response , String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition" , "attachment;filename=" + fileName);
			response.addHeader("Pargam" , "no-cache");
			response.addHeader("Cache-Control" , "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
